
package com.scalar.chiptrack.jobs.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.jobs.Job;
import com.scalar.chiptrack.jobs.JobRunner;
import com.scalar.chiptrack.jobs.forms.JobAdminForm;
import com.scalar.chiptrack.jobs.dao.JobDAO;



public class JobAdminAction extends ChipTrackAction {

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
                                  throws Exception {
    
        JobRunner jobRunner = JobRunner.getInstance();
        JobAdminForm jobAdminForm = (JobAdminForm) form;
        try {
            // LOAD ALL JOBS FROM DATABASE
            ArrayList allJobs = JobDAO.loadAllJobs();
            if (allJobs == null) allJobs = new ArrayList();

            HashMap jobsMap = new HashMap ();

            if (allJobs.size() != 0) {
                int jobCount = allJobs.size();
                Job job = null;

                for (int l=0; l<jobCount; l++) {
                    job = (Job) allJobs.get(l);
                    jobsMap.put(job.getId()+"", job);
                }
            }

            String action = request.getParameter ("action");
            if (action == null) {
                action = "refresh";
            }

            System.out.println ("ACTION = " + action);
            String[] jobIds = request.getParameterValues ("jobId");


            if (action.equalsIgnoreCase("ping") == true) {
                LinkedHashMap info = new LinkedHashMap();
                info.put ("Job Scheduler", jobRunner.getStatusAsString());
                info.put ("Job Poller", jobRunner.getJobPollerStatus());
                info.put ("Job Cleanup Thread", jobRunner.getCleanupJobStatus());
                
                request.setAttribute (SessionKeys.INFO_MESSAGES, info);
            }
            
            else if (action.equalsIgnoreCase("Start Job Scheduler") == true) {
                JobDAO.updateSchedulerStatus( Boolean.TRUE );
                jobRunner.start();
            }

            else if (action.equalsIgnoreCase("Stop Job Scheduler") == true) {
                JobDAO.updateSchedulerStatus( Boolean.FALSE );
                jobRunner.stop();
            }

            else if (action.equalsIgnoreCase("start")) {

                if ((jobIds != null) && (jobIds.length != 0)) {

                    Job job = null;
                    for (int k=0; k<jobIds.length; k++) {
                        try {
                            job = (Job)jobsMap.get(jobIds[k]);

                            if (job != null) {
                                job.setStartTime (null);    // execute right now
                                jobRunner.execute (job);
                                System.out.println (job.getName() + " has been started");
                            }
                        }
                        catch (Exception e) {
                            System.out.println ("Could not start " + job.getName());
                            e.printStackTrace();
                        }
                    }
                }
            }

            else if (action.equalsIgnoreCase("abort")) {

                if ((jobIds != null) && (jobIds.length != 0)) {
                    Job job = null;

                    for (int k=0; k<jobIds.length; k++) {
                        job = (Job)jobsMap.get(jobIds[k]);
                        jobRunner.abort (Integer.parseInt(jobIds[k]));
                        System.out.println (job.getName() + " [ID = " + jobIds[k] + "] has been stopped");
                    }
                }
            }

            else if (action.equalsIgnoreCase("remove")) {

                String[] jobStatusIds = request.getParameterValues ("jobStatusId");
                JobDAO.removeJobById (jobStatusIds);

                //for (int k=0; k<jobStatusIds.length; k++) {
                //    System.out.println ("Job (ID = " + jobStatusIds[k] + ") has been removed");
                //}
            }

            // CLASSIFY RUNNING/DONE JOBS BASED ON THEIR STATUS
            ArrayList runningJobs = new ArrayList();
            ArrayList doneJobs    = new ArrayList();

            ArrayList jobStatusList = JobDAO.loadAllJobStatusInfo();
            if ((jobStatusList != null) && (jobStatusList.size() != 0)) {

                Job job = null;
                int size = jobStatusList.size();
                String status = null;

                for (int i=0; i<size; i++) {

                    job = (Job) jobStatusList.get (i);
                    status = job.getStatus();

                    if (status.equalsIgnoreCase(Job.STATUS_RUNNING)) {
                        runningJobs.add (job);
                    }
                    if ((status.equalsIgnoreCase(Job.STATUS_DONE)) || (status.equalsIgnoreCase(Job.STATUS_FAILED )) || (status.equalsIgnoreCase(Job.STATUS_ABORTED)))
                    {
                        if(jobAdminForm.getJobId()<=0) //all jobs
                        {
                            if( jobAdminForm.getStatus() == null || "All".equalsIgnoreCase(jobAdminForm.getStatus())) //all status
                            {
                                doneJobs.add (job);
                            }
                            else if(jobAdminForm.getStatus().equalsIgnoreCase(status))
                            {
                                doneJobs.add (job);
                            }
                        }
                        else if(jobAdminForm.getJobId()==job.getId() )
                        {
                            if("All".equalsIgnoreCase(jobAdminForm.getStatus())) //all status
                            {
                                doneJobs.add (job);
                            }
                            else if(jobAdminForm.getStatus().equalsIgnoreCase(status))
                            {
                                doneJobs.add (job);
                            }
                        }
                    }
                }
            }


            request.setAttribute("schedulableJobs", allJobs);
            request.setAttribute("runningJobs", runningJobs);
            request.setAttribute("doneJobs", doneJobs);
            request.setAttribute("jobStatusList", jobStatusList);
            request.setAttribute("jobslist", jobStatusList);
            request.setAttribute("statusList", jobAdminForm.getStatusList());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return (mapping.findForward("success"));
    }
}
